package ru.reaperoq.inventory.screens.main.admin.users

import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import models.LocationUi
import models.shared.UserUi
import ru.reaperoq.inventory.components.textField.DropDownTextField

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChangeUserLocationDialog(
    modifier: Modifier = Modifier,
    user: UserUi,
    locations: List<LocationUi>,
    onDismissRequest: () -> Unit,
    onConfirm: (id: Int, locId: Int) -> Unit
) {
    var locationName by remember { mutableStateOf(user.location?.name ?: "") }
    val locationId by remember(locationName) {
        mutableStateOf(
            locations.find { it.name == locationName }?.id
        )
    }
    var error by remember(locationId) { mutableStateOf(false) }

    AlertDialog(
        modifier = modifier,
        onDismissRequest = onDismissRequest,
        title = {
            Text(buildAnnotatedString {
                append("Изменить локацию ")
                withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                    append(user.username)
                }
            })
        },
        text = {
            DropDownTextField(
                data = locations.map { it.name },
                value = locationName,
                labelText = "Локация",
                readOnly = true,
            ) {
                locationName = it
            }
        },
        dismissButton = {
            TextButton(onClick = onDismissRequest) {
                Text(text = "Отмена")
            }
        },
        confirmButton = {
            Button(onClick = {
                if (locationId == null) {
                    error = true
                } else {
                    onConfirm(locationId!!, user.id)
                    onDismissRequest()
                }
            }) {
                Text(text = "Добавить")
            }
        }
    )
}